import React, { Component } from "react";
import { withRouter } from 'react-router-dom'

import {Button, Modal} from 'antd'

import storageUtils from '../../utils/storageUtils'
import { formateDate } from "../../utils/dateUtils";
import memoryUtils from '../../utils/memoryUtils'
import menuList from '../../config/menuConfig'

import './index.less'

/**
 * 左侧导航的组件
 */
class Header extends Component {
    state = {
        currentTime: formateDate(Date.now()),    // 当前时间，字符串格式
        dayPictureUrl: '',    // 天气图片的url
        weather: ''
    }
    getTime = () => {
        // 每隔1秒获取当前时间，并更新状态currentTime
        this.intervalId = setInterval(() => {
            const currentTime = formateDate(Date.now());
            this.setState({ currentTime })
        }, 1000)
    }

    getTitle = () => {
        // 得到当前请求路径
        const path = this.props.location.pathname;
        let title
        menuList.forEach((item) => {
            if (item.key === path) {
                // 如果当前item的key与path一样，item的title就是要显示的title
                title = item.title
            } else if (item.children) {
                const cItem = item.children.find(cItem => cItem.key === path);
                if (cItem) {
                    title = cItem.title;
                }
            }
        })
        return title;
    }

    //第一次render执行之后执行
    //一般执行异步操作（发送ajax请求、启动定时器）
    componentDidMount() {
        // 获取当前时间
        this.getTime();
    }
    /*
      当前组件卸载之前调用
    */
    componentWillUnmount() {
        // 清除定时器
        clearInterval(this.intervalId)
    }

    /*
  退出登陆
   */
    logout = () => {
        // 显示确认框
        Modal.confirm({
            content: '确定退出吗?',
            onOk: () => {
                console.log('OK', this)
                // 删除保存的user数据
                storageUtils.removeUser()
                memoryUtils.user = {}

                // 跳转到login
                this.props.history.replace('/login')
            }
        })
    }
    render() {
        const { currentTime } = this.state
        const username = memoryUtils.user.username;
        const title = this.getTitle();
        return (
            <div className="header">
                <div className="header-top">
                    <span>欢迎，{username}</span>
                    <Button type="link" onClick={this.logout}>退出</Button>
                </div>
                <div className="header-bottom">
                    <div className="header-bottom-left">
                        {title}
                    </div>
                    <div className="header-bottom-right">
                        <span>{currentTime}</span>
                        {/* <img src={dayPictureUrl} alt="weather" />
                        <span>{weather}</span> */}
                    </div>
                </div>
            </div>
        )
    }
}

export default withRouter(Header)